package com.teemo.sprinboot06mybatiscrud.controller;

import com.teemo.sprinboot06mybatiscrud.mapper.MachineMapper;
import com.teemo.sprinboot06mybatiscrud.utils.MyJsonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @Author YIFan
 * @Date 2022/2/11 14:21
 * @Version 1.0
 * @DESC //TODO
 */
@RestController
public class FileController {

    MyJsonResponse myJsonResponse = new MyJsonResponse();

    /**
     * 项目端口
     */
    @Value("${server.port}")
    public String port;

    @Autowired
    MachineMapper machineMapper;

    @PostMapping("111")
    public String dawd(){
        return "Dwad";
    }

    @PostMapping(value = "/uploadFile")
    public String upload(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }
        // 获取最大id作为文件后缀id
        Integer machineMaxID = machineMapper.getMachineMaxID();

        // 获取文件的名称
        String originalFilename = file.getOriginalFilename();
        // 文件后缀 例如：.png
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 根路径，在 resources/static/upload
        try {
            String basePath = System.getProperty("user.dir")+"\\pic\\";
            // 获取文件对象
            String fileName = "type_" + machineMaxID + ".png";
            File newfile = new File(basePath+fileName);
            // 完成文件的上传
            file.transferTo(newfile);
            // 返回绝对路径
            return myJsonResponse.make200Resp(MyJsonResponse.default_200_response, "http://localhost"  + ":" + port  + "/pic/" + fileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.err.println("==============上传失败==============");
        }

        return "上传失败！";
    }
}
